package pratice.fengzhongye.interview;

import sun.applet.Main;

import java.util.ArrayList;
import java.util.List;

/**
 * 问题：
 * 1.谁去调用notifyAll?
 * 2.等待的时候要用while!为了下一次醒来在去判断
 *
 * @author 吴宇亮 on 2019/2/19 0019 15:11
 */
public class Lesson11_Thread2 {

    public static void main(String[] args) {

        Product p = new Product();

        List<Runnable> increaseList = new ArrayList<>();
        List<Runnable> decreaseList = new ArrayList<>();
        for (int i = 0; i < 10; i++){
            increaseList.add(() -> {
                while(true) p.increase();
            });
            decreaseList.add(() ->{
                while(true) p.decreset();
            });
        }

        increaseList.forEach(item -> {
            new Thread(item).start();
        });
        decreaseList.forEach(item -> {
            new Thread(item).start();
        });
    }
}

class Product{

    private static final int MIN_AMOUNT = 0;
    private static final int MAX_AMOUNT = 10;

    int amount = 0; //产品数量

    public synchronized void increase() {
        while (amount == MAX_AMOUNT){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        amount++;
        notifyAll();

        System.out.println(amount);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void decreset() {
        while (amount == MIN_AMOUNT){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        amount--;
        notifyAll();

        System.out.println(amount);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
